﻿#region Copyright

// The contents of this file are subject to the Mozilla Public License
//  Version 1.1 (the "License"); you may not use this file except in compliance
//  with the License. You may obtain a copy of the License at
//  
//  http://www.mozilla.org/MPL/
//  
//  Software distributed under the License is distributed on an "AS IS"
//  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//  License for the specific language governing rights and limitations under 
//  the License.
//  
//  The Initial Developer of the Original Code is Robert Smyth.
//  Portions created by Robert Smyth are Copyright (C) 2008.
//  
//  All Rights Reserved.

#endregion

using System;
using System.IO.Pipes;
using NUnitGrid.Framework.Pipes.Client;


namespace NUnitGrid.Framework.Pipes.Server
{
    public class PipeServerStream : IPipeStream
    {
        private readonly NamedPipeServerStream pipe;
        private readonly IPipeStream pipeStream;
        private PipeClientStream.OnConnect onConnectCallBack;

        public PipeServerStream(NamedPipeServerStream pipe, IPipeStream pipeStream)
        {
            this.pipe = pipe;
            this.pipeStream = pipeStream;
        }

        public void Start()
        {
        }

        public void WriteLine(string message)
        {
            pipeStream.WriteLine(message);
        }

        public void Stop()
        {
            pipeStream.Stop();
        }

        public void WaitForConnection(PipeClientStream.OnConnect onConnect)
        {
            onConnectCallBack = onConnect;
            pipe.BeginWaitForConnection(OnConnect, pipe);
        }

        private void OnConnect(IAsyncResult result)
        {
            try
            {
                var pipServerStream = (NamedPipeServerStream) result.AsyncState;
                pipServerStream.EndWaitForConnection(result);

                pipeStream.Start();

                onConnectCallBack(true);
            }
            catch (Exception)
            {
            }
        }
    }
}